/**
 * 
 */
package pl.ptemich.network.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Brutusek
 *
 */
public class Client {

  private Socket clientSocket;
  
  private BufferedReader reader;
  
  private PrintStream writter;  
  
  private BufferedReader keyboardReader;
  
  public void init() {
    /*
     * Open a socket on port 2222. Open the input and the output streams.
     */
    try {
      clientSocket = new Socket("localhost", 2222);
      writter = new PrintStream(clientSocket.getOutputStream());
      reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      keyboardReader = new BufferedReader(new InputStreamReader(System.in));
    } catch (UnknownHostException e) {
      System.err.println("Don't know about host");
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to host");
    }
  }
  
  
  public void startTalking() {
    /*
     * If everything has been initialized then we want to write some data to the
     * socket we have opened a connection to on port 2222.
     */
    if (clientSocket != null && reader != null && writter != null) {
      try {

        /*
         * Keep on reading from/to the socket till we receive the "Ok" from the
         * server, once we received that then we break.
         */
        System.out.println("The client started. Type any text. To quit it type 'Ok'.");
        String responseLine;
        writter.println(keyboardReader.readLine());
        while ((responseLine = reader.readLine()) != null) {
          System.out.println(responseLine);
          if (responseLine.indexOf("Ok") != -1) {
            break;
          }
          writter.println(keyboardReader.readLine());
        }

        /*
         * Close the output stream, close the input stream, close the socket.
         */
        reader.close();
        writter.close();
        clientSocket.close();
      } catch (UnknownHostException e) {
        System.err.println("Trying to connect to unknown host: " + e);
      } catch (IOException e) {
        System.err.println("IOException:  " + e);
      }
      System.out.println("Stop client");
    }    
  }
  
}
